import * as cheerio from 'cheerio';
import type { Cheerio } from 'cheerio';
import { resolve } from 'node:path';
const url = 'https://developers.e.qq.com/v3.0/docs/enums'

function resolvePath(path: string) {
  return resolve(import.meta.dirname, path)
}

const res = await Bun.fetch(url)

const html = await res.text()

function tableToJSON(table: Cheerio<any>, $: cheerio.CheerioAPI) {
  const data: Record<string, string>[] = [];
  const headers: string[] = [];

  // 获取表头信息
  const thead = $(table).find('thead');
  if (thead.length) {
    const headerCells = $(thead).find('td');
    headerCells.each((_, cell) => {
      headers.push($(cell).text().trim());
    });
  }

  // 获取表格数据
  const tbody = $(table).find('tbody');
  if (tbody.length) {
    const rows = tbody.find('tr');
    rows.each((_, row) => {
      const rowData: Record<string, string> = {};
      const cells = $(row).find('td');
      cells.each((index, cell) => {
        const header = headers[index];
        if (header) {
          rowData[header] = $(cell).text().trim();
        }
      });
      
      // 只有当有数据时才添加
      if (Object.keys(rowData).length > 0) {
        const values = Object.values(rowData);
        if (values.length >= 2) {
          const [key, value] = values;
          data.push({[key]: value});
        }
      }
    });
  }

  return data;
}

const $ = cheerio.load(html)

const dataMap: Record<string, Record<string, string>[]> = {}
$('.colunm').each((index, item: any) => {
    const tableData = tableToJSON($(item).find('.table-hover'), $)
    const category = $(item).find('.colunm-tit').text() as string
    dataMap[category] = tableData
})

Bun.write(resolvePath('./data.json'), JSON.stringify(dataMap, null, 2))
